package redsoxfan.gamejam.base;

import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

import javax.imageio.ImageIO;

/**
 * Generate an ant script needed to build the game. This class will also generate the HTML file to load the
 * applet as well as a jsmooth file (for building an EXE) when the appropriate arguments are given. It is
 * recommended to leave this functionality to the ant script.
 * @author RedSoxFan
 * @since 20 Apr 14
 * @version 1.0
 */
public class Deploy {
	public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, IOException {
		if (args.length == 0) {
			Scanner scan = new Scanner(System.in);
			System.out.print("Fully-Qualified Game Class: ");
			String full = scan.nextLine();
			System.out.print("Code Base: ");
			String codebase = scan.nextLine();
			scan.close();
			Object g = Class.forName(full).newInstance();
			Game game;
			if (g instanceof Game)
				game = (Game) g;
			else
				throw new UnsupportedOperationException(String.format("%s is not a subclass of Game", args[0]));
			File build = new File("build.xml");
			BufferedWriter bw = new BufferedWriter(new FileWriter(build));
			bw.write(String.format("<project name=\"%s\" default=\"dist\" basedir=\".\">\n" +
				"	<description>%s</description>\n" +
				"	<property name=\"fname\" value=\"%s\" />\n" +
				"	<property name=\"codebase\" value=\"%s\" />\n" +
				"	<property name=\"gameclass\" value=\"%s\" />\n" +
				"	<property name=\"src\" location=\"src\" />\n" +
				"	<property name=\"bin\" location=\"bin\" />\n" +
				"	<property name=\"dist\" location=\"dist\" />\n" +
				"	<target name=\"compile\" depends=\"clean\" description=\"compile the source\">\n" +
				"		<mkdir dir=\"${bin}\" />\n" +
				"		<javac includeantruntime=\"false\" srcdir=\"${src}\" destdir=\"${bin}\" />\n" +
				"		<copy todir=\"${bin}\">\n" +
				"			<fileset dir=\"${src}\">\n" +
				"				<include name=\"**\" />\n" +
				"				<exclude name=\"**/*.java\"/>\n" +
				"			</fileset>\n" +
				"		</copy>\n" +
				"	</target>\n" +
				"	<target name=\"dist\" depends=\"compile\" description=\"generate the distribution\">\n" +
				"		<mkdir dir=\"${dist}\" />\n" +
				"		<jar jarfile=\"${dist}/${fname}.jar\" basedir=\"${bin}\">\n" +
				"			<manifest>\n" +
				"				<attribute name=\"Main-Class\" value=\"${gameclass}\"/>\n" +
				"				<attribute name=\"Class-Path\" value=\".\"/>\n" +
				"			</manifest>\n" +
				"		</jar>\n" +
				"		<java classname=\"redsoxfan.gamejam.base.Deploy\">\n" +
				"			<arg value=\"${gameclass}\" />\n" +
				"			<arg value=\"${codebase}\" />\n" +
				"			<arg value=\"${dist}\" />\n" +
				"			<classpath>\n" +
				"				<pathelement location=\"${dist}/${fname}.jar\" />\n" +
				"				<pathelement path=\"${java.class.path}\" />\n" +
				"			</classpath>\n" +
				"		</java>\n" +
				"		<zip destfile=\"${dist}/${fname}.zip\" basedir=\"${src}\" update=\"true\" />\n" +
				"	</target>\n" +
				"	<target name=\"clean\" description=\"clean up\">\n" +
				"		<delete dir=\"${bin}\" />\n" +
				"		<delete dir=\"${dist}\" />\n" +
				"	</target>\n" +
				"</project>", game.title(), game.title(), game.shortTitle(), codebase, full));
			bw.flush();
			bw.close();
			System.out.println("Ant file created at " + build.getAbsolutePath());
		} else if (args.length < 3) {
			System.out.println("Usage: java redsoxfan.gamejam.base.Deploy (fullyQualifiedGameClass codebase outputfolder | )\n" +
							   "If not arguments are given, an ant file will be generated.\n" +
							   "If the arguments are given, the html file will be generated. A JAR will not be created. This" +
							   "should only be called by ant.");
		} else {
			Object g = Class.forName(args[0]).newInstance();
			Game game;
			if (g instanceof Game)
				game = (Game) g;
			else
				throw new UnsupportedOperationException(String.format("%s is not a subclass of Game", args[0]));
			File folder = new File(args[2]);
			folder.mkdirs();
			File html = new File(folder.getAbsolutePath(), "index.html");
			BufferedWriter bw = new BufferedWriter(new FileWriter(html));
			bw.write(String.format("<!DOCTYPE HTML>\n" +
									"	<head>\n" +
									"		<meta charset=\"utf-8\" />\n" +
									"		<title>%s</title>\n" +
									"		<link rel=\"shortcut icon\" href=\"icon.png\" />\n" +
									"		<style>\n" +
									"			body {\n" +
									"				background-color: #111111;\n" +
									"				color: #CCCCCC;\n" +
									"				font-family: sans-serif;\n" +
									"				margin: 0px;\n" +
									"				text-align: center;\n" +
									"			}\n" +
									"			a, a:link, a:hover, a:visited {\n" +
									"				color: #00AA00;" +
									"				text-decoration: none;" +
									"			}\n" +
									"			a:hover {\n" +
									"				text-decoration: underline;" +
									"			}\n" +
									"			br {\n" +
									"				clear: both;" +
									"			}\n" +
									"		</style>\n" +
									"	</head>\n" +
									"	<body>\n" +
									"		<h1 style=\"margin: 0px;\">%s</h1>\n" +
									"		<h4 style=\"margin: 0px;\">by %s</h4>\n" +
									game.beforeApplet() +
									"		<script src=\"http://java.com/js/deployJava.js\"></script>\n" +
									"		<script>\n" +
									"			var attributes = {codebase:'%s',\n" +
									"							  code:'redsoxfan.gamejam.base.AppletWrapper.class',\n" +
									"							  archive:'%s.jar',\n" +
									"							  width:%s, height:%s};\n" +
									"			var parameters = {gameclass:'%s'};\n" +
									"			var version = '1.6';\n" +
									"			deployJava.runApplet(attributes, parameters, version);\n" +
									"		</script>\n" +
									game.afterApplet() + 
									"	</body>\n" +
									"</html>\n", game.title(), game.title(), game.authors(), args[1],
									game.shortTitle(), game.width(), game.height(), args[0]));
			bw.flush();
			bw.close();
			File jsmooth = new File(folder.getAbsolutePath(), game.shortTitle() + ".jsmooth");
			BufferedWriter jw = new BufferedWriter(new FileWriter(jsmooth));
			jw.write(String.format("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" +
					 "	<jsmoothproject>\n" +
					 "		<JVMSearchPath>registry</JVMSearchPath>\n" +
					 "		<JVMSearchPath>javahome</JVMSearchPath>\n" +
					 "		<JVMSearchPath>jrepath</JVMSearchPath>\n" +
					 "		<JVMSearchPath>jdkpath</JVMSearchPath>\n" +
					 "		<JVMSearchPath>exepath</JVMSearchPath>\n" +
					 "		<JVMSearchPath>jview</JVMSearchPath>\n" +
					 "		<currentDirectory>${EXECUTABLEPATH}</currentDirectory>\n" +
					 "		<embeddedJar>true</embeddedJar>\n" +
					 "		<executableName>%s.exe</executableName>\n" +
					 "		<iconLocation>%s</iconLocation>\n" +
					 "		<initialMemoryHeap>-1</initialMemoryHeap>\n" +
					 "		<jarLocation>%s.jar</jarLocation>\n" +
					 "		<mainClassName>%s</mainClassName>\n" +
					 "		<maximumMemoryHeap>-1</maximumMemoryHeap>\n" +
					 "		<maximumVersion></maximumVersion>\n" +
					 "		<minimumVersion></minimumVersion>\n" +
					 "		<skeletonName>Windowed Wrapper</skeletonName>\n" +
					 "		<skeletonProperties>\n" +
					 "			<key>Message</key>\n" +
					 "			<value>Java has not been found on your computer. Do you want to download it?</value>\n" +
					 "		</skeletonProperties>\n" +
					 "		<skeletonProperties>\n" +
					 "			<key>URL</key>\n" +
					 "			<value>http://www.java.com</value>\n" +
					 "		</skeletonProperties>\n" +
					 "		<skeletonProperties>\n" +
					 "			<key>SingleProcess</key>\n" +
					 "			<value>0</value>\n" +
					 "		</skeletonProperties>\n" +
					 "		<skeletonProperties>\n" +
					 "			<key>SingleInstance</key>\n" +
					 "			<value>0</value>\n" +
					 "		</skeletonProperties>\n" +
					 "		<skeletonProperties>\n" +
					 "			<key>JniSmooth</key>\n" +
					 "			<value>0</value>\n" +
					 "		</skeletonProperties>\n" +
					 "		<skeletonProperties>\n" +
					 "			<key>Debug</key>\n" +
					 "			<value>0</value>\n" +
					 "		</skeletonProperties>\n" +
					 "</jsmoothproject>", game.shortTitle(), "icon.png", game.shortTitle(), args[0]));
			jw.flush();
			jw.close();
			BufferedImage img = new BufferedImage(game.icon().getWidth(null), game.icon().getHeight(null), BufferedImage.TYPE_INT_ARGB);
			img.createGraphics().drawImage(game.icon(), 0, 0, img.getWidth(), img.getHeight(),
					0, 0, game.icon().getWidth(null), game.icon().getHeight(null), null);
			ImageIO.write(img, "PNG", new File(folder.getAbsolutePath(), "icon.png"));
		}
	}
}
